<template>
  <el-drawer v-model="_isOpen" size="820" class="tag_filter_drawer">
    <template #header>
      <div class="title">
        <div class="title_left">分类名称</div>
        <div class="title_right">标签筛选</div>
      </div>
    </template>
    <template #default>
      <div class="content">
        <div class="content_left">
          <div class="menu_list">
            <div
              v-for="item in categoryList"
              :class="`list_item ${currentCate?.categoryId === item?.categoryId ? 'item_active' : ''}`"
              :key="item?.categoryId"
            >
              <el-button @click="changeCategory(item)" link>
                {{ item.preview }}
              </el-button>
            </div>
          </div>
        </div>
        <div class="content_right" v-loading="loadingFlag">
          <div class="filter_title">通用筛选</div>
          <div class="filter_box">
            <div v-for="(item, index) in statusList.filter(it => it.isCommon === 1)" :key="item.stastsId">
              <div class="attr-item">
                <!-- 一级属性名称 -->
                <p style="color: #86909c; font-size: 16px">{{ item.stastsName }}：</p>
                <el-checkbox-group v-model="filterVal[index]" size="small">
                  <!-- 二级属性 -->
                  <div
                    v-for="(item2, index2) in item.children"
                    class="attr-wrap"
                    :key="index2"
                    :class="{ 'attr-only2': item2?.children?.length <= 0 || !item2?.children }"
                  >
                    <el-checkbox
                      :label="item2.stastsName"
                      :value="item2.stastsId"
                      :key="item2.stastsId"
                      @change="val => changeAttr2(val, item, item2, index)"
                    >
                      <template #default>
                        <p class="attr2">{{ item2.stastsName }}</p>
                        <img
                          class="active-icon"
                          v-if="item2?.children?.length <= 0 || !item2?.children"
                          src="@/assets/images/chose_icon.png"
                          alt=""
                        />
                      </template>
                    </el-checkbox>
                    <!-- 三级属性 -->
                    <div class="attr3 ml4" v-if="item2?.children?.length > 0">
                      <el-select
                        v-model="item2.select3"
                        :placeholder="filterVal.flat().includes(item2.stastsId) ? '全部' : '请选择'"
                        size="small"
                        clearable
                        style="min-width: 120px"
                        multiple
                        @change="val => changeAttr3(val, item, item2, index, index2)"
                      >
                        <el-option
                          v-for="item3 in item2.children"
                          :key="item3.stastsId"
                          :label="item3.stastsName"
                          :value="item3.stastsId"
                        />
                      </el-select>
                    </div>
                  </div>
                </el-checkbox-group>
              </div>
            </div>
          </div>
          <div class="filter_title">规格属性筛选</div>
          <div class="filter_box">
            <div class="sx_chose">
              <!-- <el-collapse v-model="collapseActive"> -->
              <!-- <el-collapse-item title="属性筛选" name="1"> -->
              <div>
                <!-- 品牌 -->
                <div class="attr-item">
                  <p style="color: #86909c; font-size: 16px">品牌：</p>
                  <el-checkbox-group v-model="brandIds" size="small">
                    <!-- 二级品牌-->
                    <div
                      v-for="(item2, index2) in statusList[0]?.brands || []"
                      class="attr-wrap"
                      :key="index2"
                      :class="{ 'attr-only2': item2?.children?.length <= 0 || !item2?.children }"
                    >
                      <el-checkbox
                        :label="item2.bandName"
                        :value="item2.brandId"
                        :key="item2.brandId"
                        @change="val => changeBrand2(val, statusList[0]?.brands, item2, index)"
                      >
                        <template #default>
                          <p class="attr2">{{ item2.bandName }}</p>
                          <img
                            class="active-icon"
                            v-if="item2?.children?.length <= 0 || !item2?.children"
                            src="@/assets/images/chose_icon.png"
                            alt=""
                          />
                        </template>
                      </el-checkbox>
                    </div>
                  </el-checkbox-group>
                </div>
                <!-- 属性 -->
                <div v-for="(item, index) in statusList.filter(it => it.isCommon === 0)" :key="item.stastsId">
                  <div class="attr-item">
                    <p style="color: #86909c; font-size: 16px">{{ item.stastsName }}：</p>
                    <el-checkbox-group v-model="filterVal[index]" size="small">
                      <!-- 二级属性 -->
                      <div
                        v-for="(item2, index2) in item.children"
                        class="attr-wrap"
                        :key="index2"
                        :class="{ 'attr-only2': item2?.children?.length <= 0 || !item2?.children }"
                      >
                        <el-checkbox
                          :label="item2.stastsName"
                          :value="item2.stastsId"
                          :key="item2.stastsId"
                          @change="
                            val => {
                              changeAttr2(val, item, item2, index);
                            }
                          "
                        >
                          <template #default>
                            <p class="attr2">{{ item2.stastsName }}</p>
                            <img
                              class="active-icon"
                              v-if="item2?.children?.length <= 0 || !item2?.children"
                              src="@/assets/images/chose_icon.png"
                              alt=""
                            />
                          </template>
                        </el-checkbox>
                        <!-- 三级属性 -->
                        <div class="attr3 ml4" v-if="item2?.children?.length > 0">
                          <el-select
                            v-model="item2.select3"
                            :placeholder="filterVal.flat().includes(item2.stastsId) ? '全部' : '请选择'"
                            size="small"
                            clearable
                            style="min-width: 120px"
                            multiple
                            @change="
                              val => {
                                changeAttr3(val, item, item2, index, index2);
                              }
                            "
                          >
                            <el-option
                              v-for="item3 in item2.children"
                              :key="item3.stastsId"
                              :label="item3.stastsName"
                              :value="item3.stastsId"
                            />
                          </el-select>
                        </div>
                      </div>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
              <!-- </el-collapse-item> -->
              <!-- </el-collapse> -->
            </div>
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <div class="footer">
        <el-button style="background: #f2f3f5; color: #424e66; border: 0" @click="reset()">重置</el-button>
        <el-button style="background: #424e66; border: 0" type="primary" @click="submit()">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup>
import { ref, computed, watch } from "vue";
import { getCategoryList } from "@/apis/shopHome/home";
import { queryStastsList } from "@/apis/search";

const props = defineProps({
  modelValue: { type: Boolean, default: true },
  categoryfatherList: {
    type: Array,
    default: () => []
  }
});

const emits = defineEmits(["update:modelValue", "confirm"]);

const _isOpen = computed({
  get: () => props.modelValue,
  set: newVal => emits("update:modelValue", newVal)
});

const categoryList = ref([]);
const statusList = ref([]);
const currentCate = ref({});
const filterVal = ref([]);
const filterVal3 = ref([]);
const loadingFlag = ref(false);
const brandIds = ref([]);
const choseList = ref([]);
const isChose = ref(false);
const choseBrandList = ref([]);

watch(
  () => _isOpen,
  val => {
    if (val) {
      console.log("是否打开", val);
      getCategory();
    }
  },
  { deep: true }
);

const getCategory = async () => {
  let { code, data } = await getCategoryList();
  console.log("分类名称===", data.reverse());
  code === 200 && convertCategoryList(data.reverse());
  currentCate.value = categoryList.value[0];
  getStatusList(currentCate.value);
};

const convertCategoryList = list => {
  categoryList.value = [];
  const ids = props.categoryfatherList.map(item => item?.categoryId);
  console.log("分类ids===", list, props.categoryfatherList, ids);
  list
    .filter(v => ids.includes(v?.categoryId))
    ?.forEach(item => {
      if (item.children.length !== 0) {
        convertCategoryList(item.children);
      }
      // if (item.preview.split("-").length > 2) {
      categoryList.value.push(item);
      // }
    });
};

const changeCategory = item => {
  reset();
  currentCate.value = item;
  getStatusList(currentCate.value);
};

const getStatusList = async item => {
  loadingFlag.value = true;
  let { code, data } = await queryStastsList({ categoryId: item?.categoryId });
  code === 200 && (statusList.value = data);
  loadingFlag.value = false;
};

const submit = () => {
  const stastsIdsStr = JSON.parse(JSON.stringify(filterVal3.value));
  for (let ids2 of filterVal.value.flat()) {
    const str = filterVal3.value.find(item => typeof item === "string" && item.includes(ids2));
    !str && stastsIdsStr.push(ids2);
  }

  console.log({
    categoryId: currentCate.value?.categoryId,
    stastsIdsStr: stastsIdsStr, //属性筛选ids
    brandIds: brandIds.value //品牌id
  });

  _isOpen.value = false;

  emits("confirm", {
    categoryId: currentCate.value?.categoryId,
    stastsIdsStr: stastsIdsStr, //属性筛选ids
    brandIds: brandIds.value //品牌id
  });
};

//2级品牌筛选
const changeBrand2 = (val, item, item2, index) => {
  console.log("这是2级品牌筛选===", brandIds.value);
  if (val) {
    choseBrandList.value.push(item2);
  } else {
    choseBrandList.value.map(it => {
      if (it.brandId == item2.brandId) {
        choseBrandList.value.splice(choseBrandList.value.indexOf(it), 1);
      }
    });
  }
};
//2级属性筛选
const changeAttr2 = (val, item, item2, index) => {
  // console.log("这是2级属性筛选===", item);
  if (val) {
    choseList.value.push(item2);
  } else {
    choseList.value.map(it => {
      if (it.stastsId == item2.stastsId) {
        choseList.value.splice(choseList.value.indexOf(it), 1);
      }
    });
  }
  console.log(choseList.value, "选中的数据", val);
  // return

  //二级选中的属性id重新排序，按照接口返回的属性顺序排
  let sortArr = [];
  filterVal.value.map((arr, i) => {
    if (index === i) {
      let Arr = [];
      if (arr) {
        for (let ids of arr) {
          const _index = item.children.findIndex(child => child.stastsId == ids);
          if (_index >= 0) {
            Arr[_index] = ids;
          }
        }
      }
      sortArr[index] = Arr;
    }
  });
  filterVal.value[index] = sortArr[index];

  if (!val) {
    item2.select3 = null;
  }

  let ARR = [];
  for (let attr1 of statusList.value) {
    for (let attr2 of attr1.children) {
      if (attr2.select3 && attr2.select3?.length > 0) {
        attr2.select3.map(obj => {
          ARR.push(attr2.stastsId + "-" + obj);
        });
      }
    }
  }
  filterVal3.value = ARR;
};

// 3级属性筛选
const changeAttr3 = (val, item, item2, index, index2) => {
  // console.log("这是3级属性筛选===", val, item);
  isChose.value = val;
  // 先清空choseList保存的三阶数据
  let arrs = choseList.value.filter(it => it.checked == true);
  choseList.value = arrs;
  // 在次赋值三级数据给choseList
  const arr = [];
  statusList.value.map(it => {
    // console.log(it,'原始的数据');
    it.children.map(cit => {
      if (cit.select3?.length > 0) {
        cit.select3.map(obj => {
          cit.children.map(child => {
            if (obj == child.stastsId) {
              arr.push(child);
            }
          });
        });
      }
    });
  });
  // 赋值choseList三级数据
  choseList.value = [...choseList.value, ...arr];

  // 去重
  const uniqueArray = [...new Map(choseList.value.map(item2 => [item2.stastsId, item2])).values()];
  choseList.value = uniqueArray;
  // 如果为arr为0清空三级数据
  if (arr.length <= 0) {
    const arr = choseList.value.filter(item2 => item2.checked == true);
    choseList.value = arr;
  }
  console.log(choseList.value, "最后的筛选数据");
  if (val) {
    //任意选中一个3级属性，默认选中对应的二级属性
    console.log(9090909090, filterVal.value, index, index2);
    filterVal.value[index] = filterVal.value[index] || [];
    filterVal.value[index][index2] = item2.stastsId;
  }

  let ARR = [];
  for (let attr1 of statusList.value) {
    for (let attr2 of attr1.children) {
      if (attr2.select3 && attr2.select3?.length > 0) {
        attr2.select3.map(obj => {
          ARR.push(attr2.stastsId + "-" + obj);
        });
      }
    }
  }
  filterVal3.value = ARR;
};

const reset = () => {
  filterVal.value = [];
  filterVal3.value = [];
  brandIds.value = [];
};
</script>
<style lang="scss">
.tag_filter_drawer {
  .el-checkbox-group {
    gap: 6px;
  }
  .el-drawer__header {
    margin-bottom: 20px !important;
  }
  .el-drawer__body {
    overflow: visible;
    padding: 0 !important;
  }
  border-radius: 10px 0 0 10px;
  .title {
    display: grid;
    grid-template-columns: 180px 560px;
    gap: 40px;
    .title_left,
    .title_right {
      box-sizing: border-box;
      font-size: 18px;
      line-height: 24px;
      color: #131414;
      font-weight: 700;
    }
  }
  .content {
    display: grid;
    height: 100%;
    grid-template-columns: 220px 600px;
    grid-template-rows: 100%;
    height: calc(100vh - 140px);
    overflow-y: auto;
    overflow-x: hidden;
    .content_left::before {
      content: "";
      display: block;
      border-left: 1px solid #e1e6ed;
      width: 0;
      position: absolute;
      left: 220px;
      bottom: 0px;
      height: calc(100% + 116px);
    }
    .content_left {
      .menu_list {
        color: #86909c;
        .list_item {
          padding: 3px 20px;
          margin: 13px 0;
          .el-button > span {
            line-height: 22px;
          }
        }
        .item_active {
          background: #edf1f4;
          .el-button > span {
            color: #3d3d3d;
          }
        }
      }
    }
    .content_right {
      padding: 20px;
      .filter_title {
        font-size: 16px;
        color: #3d3d3d;
        font-weight: 700;
      }
      .filter_box {
        margin: 20px 0;
      }
    }
  }
  .footer {
    box-sizing: border-box;
    width: 100%;
    padding-left: 200px;
    display: flex;
    justify-content: center;
    .el-button {
      width: 108px;
      height: 36px;
    }
  }
}
</style>
<style lang="scss" scoped>
@import "@/assets/styles/index";
.attr3 {
  display: flex;
  .child_name {
    margin: 0 10px 0 0;
  }
}
:deep(.el-collapse-item__header) {
  display: none;
}
.more_btn {
  display: flex;
  justify-content: end;
  flex: 1;
  .more_btn_box {
    display: flex;
    gap: 10px;
    font-size: 16px;
    font-weight: 700;
    align-items: center;
  }
  .icon {
    width: 16px;
    height: 16px;
    transition: transform 0.5s ease-in-out;
  }
  .more_active {
    transform: rotate(-180deg);
  }
}
.sx_chose {
  box-sizing: border-box;
  border-top: 0px;
  padding-top: 0px;
  overflow: hidden;
  :deep(.el-collapse-item__header) {
    display: block !important;
    text-align: left;
    position: relative;
    i {
      position: absolute;
      right: 0;
      top: 50%;
    }
  }
}
.collapse_active {
  max-height: 300px;
  padding-top: 20px;
  border-top: 1px solid #eef1f4;
}
.secondary {
  :deep(.el-checkbox__input) {
    display: none !important;
  }
  :deep(.el-checkbox) {
    padding: 0 !important;
  }
  .attr2 {
    color: #4e5969 !important;
  }
  :deep(.el-select__wrapper) {
    height: 32px !important;
  }
}
:deep(.el-select__wrapper) {
  height: 32px !important;
}
:deep(.el-collapse) {
  border: none !important;
}
.active {
  border: 1px solid #000;
}
:deep(.el-checkbox__label) {
  padding: 0 !important;
}
:deep(.is-checked) {
  color: #000 !important;
}
.child_name {
  width: auto;
  // height: 100%;
  font-size: 14px;
  color: #3d3d3d;
  display: flex;
  align-items: center;
  cursor: pointer;
  background: #ffffff;
  box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.16);
  border-radius: 4px 4px 4px 4px;
  margin-right: 6px;
  // padding: 5px 19px;
  // overflow: hidden;
  position: relative;
  .attr2 {
    color: #000 !important;
  }
  .check {
    position: absolute;
    right: -1px;
    bottom: -2px;
    img {
      width: 20px;
    }
  }
  :deep(.el-checkbox__input) {
    display: none !important;
  }
}
p,
h1 {
  margin: 0;
  padding: 0;
  font-weight: normal;
}

:deep(.el-collapse-item__header) {
  font-size: 16px;
  color: #3d3d3d;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;

  .attr-wrap {
    display: flex;
    align-items: center;
    // border: 1px solid #dcdfe6;
    border-radius: 4px;
    min-height: 32px;
    padding: 1px 8px;
    margin-bottom: 0px;
    .el-checkbox__label {
      font-size: 14px;
      padding-left: 0;
      margin-right: 8px;
    }
    .el-checkbox.el-checkbox--small {
      border-bottom: 1px solid transparent;
      &.is-checked {
        .el-checkbox__label {
          border-bottom: 1px solid #000;
          line-height: 30px;
        }
      }
    }
    &.attr-only2 {
      box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.16);
      position: relative;
      padding: 1px 0;
      .active-icon {
        display: none;
      }
      .el-checkbox__label {
        margin-right: 0;
      }
      .el-checkbox.el-checkbox--small {
        padding: 1px 20px;
        border: 1px solid transparent;
        border-radius: 4px;
        height: 30px;
        line-height: 30px;
        &.is-checked {
          border: 1px solid #000;
          .active-icon {
            display: block;
            position: absolute;
            width: 20px;
            height: 20px;
            right: 0px;
            bottom: 0px;
          }
          .el-checkbox__label {
            border-bottom: none;
          }
        }
      }
    }

    .el-checkbox__input {
      display: none;
    }
    .attr3 {
      min-width: 120px;
    }

    &:not(:last-of-type) {
      margin-right: 8px;
    }
  }
}

:deep(.el-checkbox.el-checkbox--small.is-bordered) {
  height: auto;
  height: 32px;

  .el-checkbox__label {
    .attr-wrap {
      display: flex;
      align-items: center;
    }
  }
}
:deep(.el-collapse-head-5) {
  height: 0px !important;
}
.attr-item {
  display: flex;
  align-items: center;
  padding-bottom: 16px;
  p {
    white-space: nowrap;
  }
}
.reset_box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  p {
    font-size: 16px;
    color: #3d3d3d;
  }
}
</style>
